/*
 * AudioMgr.java
 *
 * Created on March 22, 2006, 6:18 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package Media;

import Comm.Util.Logger;
import Experience.*;
import javax.microedition.lcdui.Canvas;

import java.util.Vector;

import javax.microedition.media.control.*;
import javax.microedition.media.*;
import javax.microedition.rms.*;

import java.io.IOException;

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

/**
 *
 * @author dmgreen
 */
public class AudioMgr implements PlayerListener {
    
    Canvas myCanv = null;
    
    private Player myPlayer;
    private Player myPlaybackPlayer;
    private RecordControl myControl;
    
    //will be used to store the contents of a record
   
    private ByteArrayOutputStream output = new ByteArrayOutputStream();
    private RecordStore outputRS = null;
    private String RS_TITLE = "audio_clips";
    
    private byte[] last_audio_clip;
    
    /** Creates a new instance of AudioMgr */
    public AudioMgr(Canvas audiocanv) {
        myCanv = audiocanv;
        initialize();
    }
    
    public void initialize() {
        
        //this function never gets called
        // was tyhere something wrong on the 6600 how this didn't work if
        // if it wasn't called write before recording ?~!?'
            
        try {
            myPlayer = Manager.createPlayer("capture://audio?encoding=amr");
            myPlayer.realize();                  
            myControl = (RecordControl) myPlayer.getControl("RecordControl"); 
        }

        catch (IOException ioe) { 
            Logger.getLog().addLogMessage("Got an IOException: " + ioe.toString(), Logger.MSG_ERROR);
            return;
        }
        catch (MediaException me) { 
         Logger.getLog().addLogMessage("Got a MediaException: " + me.toString(), Logger.MSG_ERROR);
         return;
        }
        catch(SecurityException se) {
            Logger.getLog().addLogMessage("Got a SecurityException: " + se.toString(), Logger.MSG_ERROR);
           return;
        }
        
        /*
        try {
            outputRS = RecordStore.openRecordStore(RS_TITLE, true);
        }
        catch (Exception e) {
            Logger.log(e.toString());
        }
         */
        
      }
    
    public void startRecording() {
         
        // this used to be in the initialize method !
        //to ADDBACK
        
        output.reset();
 
        myControl.setRecordStream(output);
        myControl.startRecord();
        
        //instead of just stopping myPlayer in close(), should stop and deallocate it!
        // then start and reallocate it here!
        try { 
            myPlayer.prefetch();
            myPlayer.start(); 
        }
        catch (MediaException me) { 
            Logger.getLog().addLogMessage("MediaException when starting " + me.toString(), Logger.MSG_ERROR);
        }  
      }
    
    public byte[] stopRecording() {
       
        myControl.stopRecord();
       //((AudioScreen) myCanv).showMsg("Stopped Recording");
          
        try { 
            myControl.commit(); 
        }
        catch (IOException ioe) {
            Logger.getLog().addLogMessage("Committing error: " + ioe.toString(), Logger.MSG_ERROR);
            return null;
        }
        
       // should this be close or stop ?~?
       try { 
            myPlayer.stop();
            myPlayer.deallocate();
            //((AudioScreen) myCanv).showMsg("Closed");
            
        }
        catch (MediaException me) {
            Logger.getLog().addLogMessage("ME when stopping player: " + me.toString(), Logger.MSG_ERROR);
            return null;
       }
       
        last_audio_clip = output.toByteArray();
        
        // probably redundant to call reset here - implicit in commit, i think?
        //((AudioScreen) myCanv).showMsg("Finished function"); 
    
        return output.toByteArray();
    }

    public void playRecording() {
        
        try {
            
            if (last_audio_clip != null) {
                //byte[] lastClip = (byte[]) myAudioClips.elementAt(0);
                ByteArrayInputStream input = new ByteArrayInputStream(last_audio_clip);
            
                myPlaybackPlayer = Manager.createPlayer(input , "audio/x-amr");
                myPlaybackPlayer.realize();
                myPlaybackPlayer.setLoopCount(1);
                myPlaybackPlayer.addPlayerListener(this);
                myPlaybackPlayer.start();
            }
        } 
       catch (IOException ioe){
            ((AudioScreen) myCanv).displayError(ioe.toString());
        } 
        catch (MediaException me) {
            ((AudioScreen) myCanv).displayError(me.toString());
        }   
        //what if it gets to the end before they stop ?
    }
        
    //hafta implement a player listener somewhere ?
    
    public void stopPlaying() {
       try  {
           if (myPlaybackPlayer != null) {
                myPlaybackPlayer.stop();
                myPlaybackPlayer.close();
           }
        }
        catch (MediaException me) {
            ((AudioScreen) myCanv).displayError(me.toString());
       }
       
    }
    
    public void close() {
        if (myPlayer != null) {
            try {
                myPlayer.stop();
                myPlayer.deallocate();
            }
            catch (MediaException me) {
                Logger.getLog().addLogMessage("Error stopping myPlayer", Logger.MSG_ERROR); 
            }
                
        }
        if (myPlaybackPlayer != null) {
            myPlaybackPlayer.close();
        
        }
    }
    
    public void playerUpdate(Player player, String event, Object eventData) {
        if (event == PlayerListener.END_OF_MEDIA) {
                ( (AudioScreen) myCanv).doStopPlaying();
         }
        }
}

